package com.example.volleyball.Tools;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;

import com.example.volleyball.ChangdiActivity;
import com.example.volleyball.LoginActivity;
import com.example.volleyball.R;

/**
 * 对话框的基类。
 * 注意：活动提供了一种工具来管理对话框的创建、保存和恢复
 */
public class CustomDialog extends Dialog {

    View view;
    String year, month, date, hour, name;
    Context context;
    private Button cancel;      // 取消功能键
    private Button ok;          // 确认功能键
    private EditText ed_year;   // 编辑year
    private EditText ed_month;  // 编辑month
    private EditText ed_date;   // 编辑day
    private EditText ed_hour;   // 编辑hour
    private EditText ed_name;   // 编辑姓名
    private DataDB db;
    private DBTools tools;

    public CustomDialog(@NonNull Context context) {
        super(context);
        this.context = context;
        view = LayoutInflater.from(context).inflate(R.layout.dialog, null, false);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(view);
        init();
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 关闭此对话框，将其从屏幕上移除
                dismiss();
            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveEdit();
                // 保存到数据库
                tools.insert(LoginActivity.account, year + "-" + month + "-" + date, ChangdiActivity.field, hour + "小时", name);
                // 然后再把这些信息初始化为空字符串
                ed_hour.setText("");
                ed_date.setText("");
                ed_month.setText("");
                ed_year.setText("");
                ed_name.setText("");
                dismiss();
            }
        });
    }

    /**
     * 定义成员变量与 view界面进行绑定
     */
    private void init() {
        db = new DataDB(context, "Data.db", null, 1);
        tools = new DBTools(db);
        cancel = findViewById(R.id.cancel);
        ok = findViewById(R.id.fix);
        ed_year = findViewById(R.id.year);
        ed_date = findViewById(R.id.date);
        ed_month = findViewById(R.id.hour);
        ed_name = findViewById(R.id.name);
        ed_hour = findViewById(R.id.hour);
    }

    /**
     * 获取到 EditView编辑框的文本信息
     */
    private void saveEdit() {
        year = ed_year.getText().toString().trim();
        month = ed_month.getText().toString().trim();
        date = ed_date.getText().toString().trim();
        hour = ed_hour.getText().toString().trim();
        name = ed_name.getText().toString().trim();
    }
}
